<template>
  <div class="article-edit">
    <el-card class="!border-none" shadow="never">
      <el-page-header :content="$route.meta.title" @back="$router.back()"/>
    </el-card>
    <el-tabs class="align-middle" v-model="defaultTab" >
      <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
      >
      <el-tab-pane label="渠道信息" name="channel_info">

        <el-card class="!border-none mt-4" shadow="never">
          <div class="font-medium mb-7">基础信息</div>
          <el-form-item label="姓名" prop="real_name">
            <div class="w-80">
              <el-input
                  v-model="formData.real_name"
                  placeholder="请输入姓名"
                  type="text"
                  maxlength="100"
                  show-word-limit
                  clearable
              />
            </div>
          </el-form-item>

          <el-form-item label="头像" prop="avator">
            <div class="w-80">
              <div>
                <material-picker v-model="formData.avator" :limit="1"/>
              </div>
              <div class="form-tips">建议尺寸：200*200px</div>
            </div>
          </el-form-item>

          <el-form-item label="个人简介" prop="self_introduction">
            <div class="w-80">
              <el-input
                  v-model="formData.self_introduction"
                  placeholder="请输入个人简介"
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 6}"
                  maxlength="300"
                  show-word-limit
                  clearable
              />
            </div>
          </el-form-item>

          <el-form-item label="微信号" prop="wechat_no">
            <div class="w-80">
              <el-input
                  v-model="formData.wechat_no"
                  placeholder="请输入微信号"
                  type="text"
                  maxlength="100"
                  show-word-limit
                  clearable
              />
            </div>
          </el-form-item>

          <el-form-item label="身份证号" prop="identity_no">
            <div class="w-80">
              <el-input
                  v-model="formData.identity_no"
                  placeholder="请输入身份证号"
                  type="text"
                  maxlength="100"
                  show-word-limit
                  clearable
              />
            </div>
          </el-form-item>

          <el-form-item label="手机号" prop="account">
            <div class="w-80">
              <el-input
                  v-model="formData.account"
                  placeholder="请输入手机号"
                  type="text"
                  maxlength="100"
                  show-word-limit
                  clearable
                  :disabled="!!route.query.id"
              />
            </div>
          </el-form-item>

          <el-form-item label="服务年限">
            <div class="w-80">
              <el-input
                  v-model="formData.serve_year"
                  placeholder="服务年限"
                  type="number"
                  maxlength="100"
                  show-word-limit
                  clearable
                  disabled
              />
            </div>
          </el-form-item>

          <el-form-item label="从业时间" prop="career_begin_date">
            <div class="w-80">
              <div class="block">
                <el-date-picker
                  class="w-80"
                  v-model="formData.career_begin_date"
                  type="month"
                  placeholder="请选择从业时间"
                  format="YYYY-MM"
                  value-format="YYYY-MM"
                />
              </div>
            </div>
          </el-form-item>

          <el-form-item label="公司" prop="company_name">
            <div class="w-80">
              <el-input
                  v-model="formData.company_name"
                  placeholder="请输入公司名称"
                  type="text"
                  maxlength="100"
                  show-word-limit
                  clearable
                  :disabled="formData.is_authentication"
              />
            </div>
          </el-form-item>

          <el-form-item label="企业认证" prop="is_authentication">
            <div class="w-80">
              <el-radio-group v-model="formData.is_authentication" :disabled="true">
                <!-- works when >=2.6.0, recommended ✔️ not work when <2.6.0 ❌ -->
                <!--              <el-radio value="Value 1">Option 1</el-radio>-->
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>


          <el-form-item label="地址" prop="company_address">
            <div class="w-80">
              <el-input
                  v-model="formData.company_address"
                  placeholder="请输入地址"
                  type="text"
                  maxlength="100"
                  show-word-limit
                  clearable
              />
              <el-button @click="focusAddress">地图选点</el-button>
            </div>
          </el-form-item>

          <el-form-item label="经度" prop="lon">
              <div class="w-80">
                  <el-input v-model="formData.lon" placeholder="请输入经度" type="text" maxlength="30"
                      show-word-limit clearable />
              </div>
          </el-form-item>

          <el-form-item label="纬度" prop="lat">
              <div class="w-80">
                  <el-input v-model="formData.lat" placeholder="请输入纬度" type="text" maxlength="30"
                      show-word-limit clearable />
              </div>
          </el-form-item>

          <el-form-item label="职务" prop="position">
            <div class="w-80">
              <el-input
                  v-model="formData.position"
                  placeholder="请输入职务"
                  type="text"
                  maxlength="100"
                  show-word-limit
                  clearable
              />
            </div>
          </el-form-item>

          <el-form-item label="主营业务" prop="product_cate_ids">
            <div class="w-80">
              <el-select class="w-[280px]" multiple :multiple-limit="3" v-model="formData.product_cate_ids" @change="changeProductCate">
                <!-- <el-option label="全部" value /> -->
                <el-option  v-for="(item) in product_cate_list " :label="item.name" :value="item.id.toString()" :key="item.id.toString()"/>
              </el-select>
            </div>
          </el-form-item>

         <el-form-item label="标签" prop="tag_ids">
            <!-- <div class="w-80">
              <el-checkbox-group v-model="formData.tag_ids">
                <el-checkbox  v-for="item in optionsData.tag_list" :label="item.id.toString()" :value="item.id.toString()" :key="item.id.toString()">
                  {{item.name}}
                </el-checkbox>
              </el-checkbox-group>
            </div> -->
            <div style="width: 60%;">
              <el-tabs v-model="activeName" class="demo-tabs">
                <el-tab-pane :label="item.name" :name="index" v-for="(item, index) in chooseLists">
                  <el-checkbox-group v-model="item.tag_ids" :max="3">
                    <el-checkbox  v-for="itemC in item.tag_list" :label="itemC.id.toString()" :value="itemC.id.toString()" :key="itemC.id.toString()">
                      {{itemC.name}}
                    </el-checkbox>
                  </el-checkbox-group>
                  <div v-if="item.tag_list.length == 0" style="color:#999999;">暂无标签</div>
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-form-item>
          <div class="font-medium mb-2">上传凭证</div>
          <div class="mb-2">为展示渠道接单能力，渠道需要对选择的业务类型上传截图证明，每类型两张</div>
          <template v-for="(item, index) in cate_poof" :key="item.product_cate_id">
            <el-form-item :label="item.name" :prop="`cate_poof${index}`">
              <div class="w-[500px]">
                <div>
                  <material-picker v-model="item.proofs" :limit="5"/>
                </div>
              </div>
            </el-form-item>
          </template>

          <el-form-item label="所属场地" prop="office_place_id">
            <div class="w-80">
              <el-select class="w-[280px]"   v-model="formData.office_place_id">
                <el-option label="全部" :value="0" />
                <el-option  v-for="(item) in office_place_list" :label="item.name" :value="item.id" :key="item.id"/>
              </el-select>
            </div>
          </el-form-item>

          <el-form-item label="渠道等级" prop="start_level">
            <div class="w-80">
              <el-select class="w-[280px]"  v-model="formData.start_level">
                <el-option label="全部" value />
                <el-option label="1星" :value="1" :key="1"/>
                <el-option label="2星" :value="2" :key="2"/>
                <el-option label="3星" :value="3" :key="3"/>
                <el-option label="4星" :value="4" :key="4"/>
                <el-option label="5星" :value="5" :key="5"/>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="限时权益" prop="is_limit_time_benefit">
            <div class="w-80">
              <el-radio-group v-model="formData.is_limit_time_benefit">
                <!-- works when >=2.6.0, recommended ✔️ not work when <2.6.0 ❌ -->
                <!--              <el-radio value="Value 1">Option 1</el-radio>-->
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
          <el-form-item label="启用状态" prop="is_enable">
            <div class="w-80">
              <el-radio-group v-model="formData.is_enable" :disabled="!route.query.id">
                <!-- works when >=2.6.0, recommended ✔️ not work when <2.6.0 ❌ -->
                <!--              <el-radio value="Value 1">Option 1</el-radio>-->
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>


        </el-card>
      </el-tab-pane>
      <el-tab-pane label="关联产品" name="relate_product">
		<table class="dataTable" border="0" cellspacing="0">
			<tbody>
				<tr>
					<th>序号</th>
					<th>产品分类</th>
					<th>银行</th>
					<th>产品名称</th>
					<th>产品logo</th>
					<th>最高额度（万）</th>
					<th>授信年限</th>
					<th>利率类型</th>
					<th>利率值</th>
					<th>还款方式</th>
					<th>准入区域</th>
					<th>操作</th>
				</tr>
				<template v-for="(item,index) in formData.join_product_arr">
					<tr v-if="item.type!='del'" :key="'join_product_arr'+index">
						<td>{{item.id}}</td>
						<td>{{item.cate_name}}</td>
						<td>{{item.bank_name}}</td>
						<td>{{item.name}}</td>
						<td>
							<image-contain v-if="item.logo" :src="item.logo" :width="60" :height="45" :preview-src-list="[item.logo]" preview-teleported fit="contain" />
						</td>
						<td>{{item.quota}}</td>
						<td>						    
							<template v-for="(child, i) in item.credit_year" :key="i"> {{ child }}年/ </template>
						</td>
						<td>{{item.rate_type==1?'年化利率':item.rate_type==2?'日利率':''}}</td>
						<td>
							{{ item.rate_type == 1 ? ((parseInt(item.rate_start * 10000)/100).toString() + '%') : ((parseInt(item.rate_start * 100000)/100).toString() + '‰') }}
							  -
							{{ item.rate_type == 1 ? (parseInt(item.rate_end * 10000)/100).toString() + '%' : (parseInt(item.rate_end * 100000)/100).toString() + '‰' }}
						</td>
						<td>{{localGetRepaymentTypeText(item.repayment_type)}}</td>
						<td>{{localGetAccessAreasText(item.access_area_arr)}}</td>
						<td>
							<el-button type="danger" link @click="deleteProductItem(1,index,item)">删除</el-button>
              <el-button type="primary" link @click="goodChannelItem(item)">接单优势</el-button>
						</td>
					</tr>
				</template>
				<tr v-for="(item,index) in formData.join_product_arr2" :key="'join_product_arr2'+index">
					<td>{{item.id}}</td>
					<td>{{item.cate_name}}</td>
					<td>{{item.bank_name}}</td>
					<td>{{item.name}}</td>
					<td>
						<image-contain v-if="item.logo" :src="item.logo" :width="60" :height="45" :preview-src-list="[item.logo]" preview-teleported fit="contain" />
					</td>
					<td>{{item.quota}}</td>
					<td>						    
						<template v-for="(child, i) in item.credit_year" :key="i"> {{ child }}年/ </template>
					</td>
					<td>{{item.rate_type==1?'年化利率':item.rate_type==2?'日利率':''}}</td>
					<td>
						{{ item.rate_type == 1 ? ((parseInt(item.rate_start * 10000)/100).toString() + '%') : ((parseInt(item.rate_start * 100000)/100).toString() + '‰') }}
						  -
						{{ item.rate_type == 1 ? (parseInt(item.rate_end * 10000)/100).toString() + '%' : (parseInt(item.rate_end * 100000)/100).toString() + '‰' }}
					</td>
					<td>{{localGetRepaymentTypeText(item.repayment_type)}}</td>
					<td>{{localGetAccessAreasText(item.access_area_arr)}}</td>
					<td>
						<el-button type="danger" link @click="deleteProductItem(2,index,item)">删除</el-button>
					</td>
				</tr>
				<template v-if="formData.join_product_arr.length==0&&formData.join_product_arr2.length==0">
					<tr>
						<td :colspan="12" style="text-align: center; color: red;">暂无数据</td>
					</tr>
				</template>
			</tbody>
		</table>
		<el-button type="primary" @click="productAdd(formData.join_product_arr2)" class="mb-4" style="display: block; margin: 24px auto;">
			<template #icon>
				<icon name="el-icon-Plus"/>
			</template>
			<span>添加产品</span>
		</el-button>
      </el-tab-pane>
      <el-tab-pane label="协议" name="protocol_info">
		<el-form-item label="协议预览" prop="">
			 <!-- v-if="formData.id" -->
			<el-button type="primary" size="small" @click="handleSign">查看</el-button>
			<!-- <vue-office-docx src="https://docs.qq.com/doc/DQWZEWVNZWkhpTk93?is_no_hook_redirect=1" @rendered="renderingCompleted" /> -->
		</el-form-item>
		<el-form-item label="签署手机号" prop="">
			<span>{{formData.account}}</span>
		</el-form-item>
		<el-form-item label="发起签署" prop="">
			<el-radio-group v-model="formData.is_send">
			  <el-radio :label="1">发起</el-radio>
			  <el-radio :label="0">不发起</el-radio>
			</el-radio-group>
		</el-form-item>
      </el-tab-pane>
      </el-form>
    </el-tabs>
    <footer-btns>
      <el-button type="primary" @click="handleSave" v-prevent-reclick="3000">保存</el-button>
    </footer-btns>
	<product-popup v-if="showProduct" ref="productRef" @success="getProduct" @close="showProduct = false" />
	<agreement-popup v-model:show="showAgreement" value="渠道入驻告知书" ref="agreementRef" @close="showAgreement = false" />
  <map-area ref="mapArea" @save="mapInfo" />

  <el-dialog
              v-model="showIcon"
              title="报名费设置"
              width="400"
              @close="handleDiaClose"
      >
    <el-form
              ref="formDialog"
              :model="formDialogData"
              label-width="100"
              require-asterisk-position="right"
          >
      <el-form-item label="接单优势" prop="channel_advantage">
                  <div class="w-80">
                      <el-input
                          v-model="formDialogData.channel_advantage"
                          placeholder="请输入接单优势"
                          type="textarea"
                          maxlength="30"
                          clearable
                      />
                  </div>
              </el-form-item>
    </el-form>
    <template #footer>
              <div class="dialog-footer">
                  <el-button @click="handleDiaClose">取消</el-button>
                  <el-button v-perms="['channel.channel/editChannelAdvantage']" type="primary" @click="onSubmit">确认</el-button>
              </div>
          </template>
  </el-dialog>

  </div>
</template>

<script lang="ts" setup name="channelListsEdit">
import type {FormInstance} from 'element-plus';
import feedback from '@/utils/feedback';
import {channelDetail, channelEdit, channelAdd} from '@/api/channel/channel';
import {tagAdvantageAllList} from "@/api/channel/tag"
import { getSignLink } from '@/api/sharedoffice/orderlists';
import {getTagList} from "@/api/tag"
import {officePlaceListNoPage} from "@/api/office/officePlace"
import { productCate, editChannelAdvantage} from '@/api/product/product'
import useMultipleTabs from '@/hooks/useMultipleTabs'
import {getRoutePath} from "@/router";
import {useDictOptions} from "@/hooks/useDictOptions";
import {isEmpty} from "@/utils/util";
// import VueOfficeDocx from "@vue-office/docx";
// const renderingCompleted = () => {
// 	console.log("渲染完成");
// }
// import useAppStore from '@/stores/modules/app'
// const useApp = useAppStore()
// const optionCity:any = useApp.optionCity;
import MapArea from '@/components/map/index.vue'
const mapArea = ref()

import ProductPopup from './product.vue';
const productRef = shallowRef<InstanceType<typeof ProductPopup>>()
const showProduct = ref(false)

import AgreementPopup from './agreement.vue';
const agreementRef = shallowRef<InstanceType<typeof AgreementPopup>>()
const showAgreement = ref(false)
const handleSign = async () => {
	showAgreement.value = true;
	// try{
	// 	const data = await getSignLink({ id: formData.id });
	// 	if( data.link.url ){
	// 		window.open(data.link.url);
	// 	}else{
	// 		feedback.msgError(data.link.msg);
	// 	}
	// }catch(e){
	// 	console.log(e);
	// 	//TODO handle the exception
	// }
}
const productAdd = async (ids?: any) => {
	showProduct.value = true
	await nextTick()
	if (ids) {
		productRef.value?.setFormData({
			pid: ids
		})
	}
	productRef.value?.open('add')
}
const getProduct = (val:any)=>{
	// console.log(val);
	// formData.join_product_arr2 = val.map((item:any)=>{
	// 	item.type = 'add';
	// 	return item;
	// });
	val.forEach((item:any)=>{
		item.type = 'add';
		let isAdd = true;
		formData.join_product_arr.forEach((child)=>{
			if( child.id==item.id&&child.type!='del' ){
				isAdd = false;
			}
		});
		formData.join_product_arr2.forEach((child)=>{
			if( child.id==item.id ){
				isAdd = false;
			}
		});
		if( isAdd ){
			formData.join_product_arr2.push(item);
		}
	})
}
const deleteProductItem = (type:number,i:number,item:any)=>{
	if( type==1 ){
		item.type = 'del';
	}else{
		formData.join_product_arr2.splice(i,1);
	}
}
const route = useRoute()
const router = useRouter()
const formData:any = reactive({
  id: '',
  area_id: '',
  real_name: '',
  avator: '',
  self_introduction: '',
  wechat_no: '',
  identity_no: '',
  account: '',
  serve_year: 0,
  company_name: '',
  company_address: '',
  position: '',
  product_cate_ids: [],
  advantage_tags: [],
  tag_ids: [],
  office_place_id: '',
  start_level: '',
  is_limit_time_benefit: 0,
  is_enable: 0,
  is_authentication: 0,
  join_product_arr: [] as any[],
  join_product_arr2: [] as any[],
  is_send: 1,
  lon: '',
  lat: '',
  career_begin_date: '',
  product_cate_proofs: []
})
const validatePass0 = (rule: any, value: any, callback: any) => {
  if (cate_poof.value[0].proofs.length < 2) {
    callback(new Error('凭证最少上传两张'))
  } else {
    callback()
  }
}
const validatePass1 = (rule: any, value: any, callback: any) => {
  if (cate_poof.value[1].proofs.length < 2) {
    callback(new Error('凭证最少上传两张'))
  } else {
    callback()
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (cate_poof.value[2].proofs.length < 2) {
    callback(new Error('凭证最少上传两张'))
  } else {
    callback()
  }
}
const {removeTab} = useMultipleTabs()
const formRef = shallowRef<FormInstance>()
const rules = reactive({
  area_id: [{required: true, message: '请选择所属城市', trigger: 'blur'}],
  real_name: [{required: true, message: '请填写姓名', trigger: 'blur'}],
  avator: [{required: true, message: '请选择头像', trigger: 'blur'}],
  self_introduction: [{required: true, message: '请填写个人简介', trigger: 'blur'}],
  wechat_no: [{required: true, message: '请填写微信号', trigger: 'blur'}],
  identity_no: [{required: true, message: '请填写身份证号', trigger: 'blur'}],
  account: [{required: true, message: '请填写手机号', trigger: 'blur'}],
  serve_year: [{required: true, message: '请填写服务年限', trigger: 'blur'}],
  career_begin_date: [{required: true, message: '请选择从业时间', trigger: 'blur'}],
  company_name: [{required: true, message: '请填写公司名称', trigger: 'blur'}],
  company_address: [{required: true, message: '请填写公司地址', trigger: 'blur'}],
  position: [{required: true, message: '请填写职位', trigger: 'blur'}],
  product_cate_ids: [{required: true, message: '请选择主营业务', trigger: 'blur'}],
  office_place_id: [{required: true, message: '请选择所属场地', trigger: 'blur'}],
  start_level: [{required: true, message: '请选择等级', trigger: 'blur'}],
  is_enable: [{required: true, message: '请选择启用状态', trigger: 'blur'}],
  is_authentication: [{required: true, message: '请选择企业认证', trigger: 'blur'}],
  lon: [{ required: true, message: '请填写经度', trigger: 'blur' }],
  lat: [{ required: true, message: '请填写纬度', trigger: 'blur' }],
  cate_poof0: [{ required: true,validator: validatePass0, trigger: 'blur' }],
  cate_poof1: [{ required: true,validator: validatePass1, trigger: 'blur' }],
  cate_poof2: [{ required: true,validator: validatePass2, trigger: 'blur' }],
})
const localGetRepaymentTypeText = (repaymentTypes: number[]| null): string => {
  //1.先息后本 2.等额本息 3.等额本金
  let repaymentTypeStr = ''
  if (!isEmpty(repaymentTypes)) {
	(repaymentTypes as number[]).forEach((item,index )  => {
	  if (item == 1) {
		repaymentTypeStr += '先息后本/'
	  } else if (item == 2) {
		repaymentTypeStr += '等额本息/'
	  } else if (item == 3) {
		repaymentTypeStr += '等额本金/'
	  } else if (item == 4) {
      repaymentTypeStr += '一次性还本付息/'
    } else if (item == 5) {
      repaymentTypeStr += '随借随还/'
    }

	})
  }
  return repaymentTypeStr.slice(0, -1)
}
// 接单优势
const formDialog = shallowRef<FormInstance>()
const formDialogData:any = reactive({
  channel_advantage: '',
  product_id: ''
})
const showIcon = ref(false);
const handleDiaClose = () => {
  showIcon.value = false;
  setTimeout(function () {
      formDialog.value?.clearValidate();//消除校验,这里的setTimeOut不能去掉,去掉之后会不生效
      formDialog.value?.resetFields();
  },30);
}
const goodChannelItem = (item:any) => {
  console.log(item)
  showIcon.value = true;
  formDialogData.channel_advantage = item.channel_advantage;
  formDialogData.product_id = item.id;
}
const onSubmit = async () => {
  console.log(formData)
  console.log(formDialogData)
  await editChannelAdvantage({
    product_id: formDialogData.product_id,
    channel_extra_id: formData.id,
    channel_advantage: formDialogData.channel_advantage
  })
  showIcon.value = false;
  getDetails()
}


const localGetAccessAreasText = (accessAreaArr: Array<any>): string => {
  let accessAreaText = ''
  accessAreaArr.forEach((item, index) => {
	accessAreaText += (item?.Name)+'/'
  })
  return accessAreaText.replace(/[\\//]$/, "");
}
const defaultTab  = ref('channel_info')
const getDetails = async () => {
  const data = await channelDetail({
    id: route.query.id,
    area_id: route.query.area_id
  })
  getCateList(data.area_id)
  data.join_product_arr2 = [];
  data.is_send = 0;
  Object.keys(formData).forEach((key) => {
    //@ts-ignore
    formData[key] = data[key]
  })
  let proof_arr = formData.product_cate_proofs;
  product_cate_list.value.forEach((item:any)=>{
    proof_arr.map((itemP:any)=>{
      if (item.id == itemP.product_cate_id) {
        itemP.name = item.name;
      }
    })
  })
  formData.product_cate_proofs = proof_arr
  console.log(formData)
  getPlaceList()
  // changeTag(formData.product_cate_ids, formData.advantage_tags)
}

const product_cate_list:any = ref([])
const getCateList = async (area_id:any) => {
    const res = await productCate({area_id: area_id})
    console.log(res)
    product_cate_list.value = res
    changeTag(formData.product_cate_ids, formData.advantage_tags)
}

const onChange_city = (val:any) => {
    if (val) {
        formData.product_cate_ids = [];
        chooseLists.value = [];
        getCateList(val)
        getTag(val)
    }
}


const {optionsData} = useDictOptions<{
  // product_cate_list: any[],
  office_place_list: any[],
}>({
  // product_cate_list: {
  //   api: productCate,
  //   params:{area_id: formData.area_id}
  // },
  office_place_list: {
    api: officePlaceListNoPage,
    params:{area_id: formData.area_id}
  }
})

// const product_cate_list:any = ref([])
// const getCateList = async () => {
//   const res = await productCate({area_id: formData.area_id})
//   product_cate_list.value = res
//   changeTag(formData.product_cate_ids, formData.advantage_tags)
// }

const office_place_list:any = ref([])
const getPlaceList = async () => {
  const res = await officePlaceListNoPage({area_id: formData.area_id})
  office_place_list.value = res
}

//点击选择地址
const focusAddress = (e: any) => {
    console.log(e)
    console.log('focus')
    mapArea.value.keywords(formData.company_address);
    mapArea.value.dialogVisible(true);
}

// 地图信息返回
const mapInfo = async (data: any) => {
    console.log(data)
    formData.company_address = data.name;
    formData.lon = data.location.lng;
    formData.lat = data.location.lat;
}

const handleSave = async () => {
  await formRef.value?.validate()
  let params = JSON.parse(JSON.stringify(formData));
  params.join_product_arr = [];
  formData.join_product_arr.forEach((item:any)=>{
  	if(item.type=='del'){
  		params.join_product_arr.push({product_id:item.id,action:'del'});
  	}
  })
  formData.join_product_arr2.forEach((item:any)=>{
  	let isAdd = true;
  	params.join_product_arr.forEach((child:any,i:number)=>{
  		if( child.product_id==item.id ){
  			params.join_product_arr.splice(i,1);
  			isAdd = false;
  		}
  	})
  	if( isAdd ){
  		params.join_product_arr.push({product_id:item.id,action:'add'});
  	}
  })
  let tagArr:any = []
  chooseLists.value.forEach((item)=>{
    let obj = {
      product_cate_id: item.id,
      tags: item.tag_ids || []
    }
    tagArr.push(obj)
  })
  params.advantage_tags = tagArr
  params.product_cate_proofs = cate_poof.value;
  if (route.query.id) {
    await channelEdit(params)
  } else {
    await channelAdd(params)
  }
  removeTab()
  router.back()

}
// 默认选中第一个tabs
const activeName = ref(0)
// 新增标签显示的数据
let tagList = ref([] as any[])
const getTag = async (area_id = route.query.area_id) => {
  const data = await tagAdvantageAllList({area_id:area_id})
  tagList.value = data;
  console.log(data)
}
const chooseLists = ref([] as any[])
const cate_poof = ref([] as any)
// 主营业务选中数据发生变化
const changeProductCate = (val: any) => {
  changeTag(val)
}
const changeTag = (val: any[], advantage_tags: any[] = []) => {
  console.log(val)
  console.log(product_cate_list.value)

  console.log(advantage_tags)
  chooseLists.value = [];
  cate_poof.value = [];
  let chooseCate = [] as any[];
  // 选择的主营业务 [1,2,3]
  val.forEach((item: any, index) => {
   
    product_cate_list.value.forEach((child: any) => {
      if (item == child.id) {
        child.tag_list = []
       
        if (route.query.id) {
          child.tag_ids = advantage_tags[index]?.tags
        }
        console.log(child)
        chooseCate.push(child)
      }
    });
  })
  console.log(chooseCate)
  // 上面选出的主营业务对象详细信息
  chooseCate.forEach((item: any) => {
    tagList.value.forEach((child: any) => {
      if (child.product_cate_ids.indexOf((item.id).toString()) != -1 && child.is_enable == 1) {
        item.tag_list.push(child)
      }
    });
    chooseLists.value.push(item)
  })

  chooseCate.forEach((item:any)=>{
    let obj = {
      product_cate_id: item.id,
      proofs: [],
      name: item.name
    }
    formData.product_cate_proofs.forEach((itemP:any)=>{
      if (item.id == itemP.product_cate_id) {
        obj.proofs = itemP.proofs;
      }
    })
    cate_poof.value.push(obj)
    console.log(cate_poof.value)
  })
}
getTag()

route.query.id && getDetails()
</script>
<style scoped lang="scss">
::v-deep .el-tabs__nav-wrap{
  overflow-x: auto ;
  width: 86% ;
  margin-left: 10px ;
}
::v-deep .el-tabs__nav-wrap::after{
  display: none ;
}
::v-deep .el-input__wrapper{
  width: 300px;
}
</style>